package cn.edu.zafu.bigdata.hdb;
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        String serverAddress = "localhost"; // 服务器 IP 地址
        int port = 12345; // 服务器端口号

        try (Socket socket = new Socket(serverAddress, port);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("已连接到聊天服务端。");

            // 创建一个线程用于接收服务端消息
            new Thread(() -> {
                String response;
                try {
                    while ((response = in.readLine()) != null) {
                        System.out.println(response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 循环发送消息到服务端
            String userInput;
            while (true) {
                userInput = scanner.nextLine();
                out.println(userInput);
                // 可以添加退出条件
                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
